﻿using System;
using Newtonsoft.Json.Linq;
using TrinityAPI.Base;
using TrinityAPI.Base.Tools;
using TrinityAPI.Base.Models;
using Jd.Api.Request;
using Jd.Api;

namespace JingDong.Open.Platform
{
    public class GetOrderList : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            try
            {
                var request = args.Length > 0 ? args[0] as JObject : dataset.GetJsonObject("request");
                var constant = dataset.GetJsonObject("constant");
                var extendProps = request.GetJsonObject("extendProps");
                var jingdongAPIConfig = constant.GetJsonObject("jingdongAPIConfig");

                var apiParams = extendProps.GetJsonObject("params");
                string eShopCode = extendProps.GetJsonObjectStringValue("eShopCode");
                string version = extendProps.GetJsonObjectStringValue("version");
                string url = jingdongAPIConfig.GetJsonObjectStringValue("url");
                string appKey = jingdongAPIConfig.GetJsonObjectStringValue("app_key");
                string appSecret = jingdongAPIConfig.GetJsonObjectStringValue("app_secret");

                if (string.IsNullOrWhiteSpace(url) || string.IsNullOrWhiteSpace(appKey) || string.IsNullOrWhiteSpace(appSecret))
                    throw new BaseException("@0002", "");

                if (string.IsNullOrWhiteSpace(eShopCode))
                    throw new BaseException("@3004", "");

                string accessToken = GetAccessToken.GetToken(eShopCode, constant);

                var client = new DefaultJdClient(url, appKey, appSecret);

                PopOrderSearchRequest orderRequest = new PopOrderSearchRequest();
                if (apiParams.ContainsKey("dateType"))
                    orderRequest.dateType = apiParams["dateType"].ToString();
                if (apiParams.ContainsKey("sortType"))
                    orderRequest.sortType = apiParams["sortType"].ToString();
                if (apiParams.ContainsKey("start_date"))
                    orderRequest.startDate = apiParams["start_date"].ToString();
                if (apiParams.ContainsKey("end_date"))
                    orderRequest.endDate = apiParams["end_date"].ToString();
                if (apiParams.ContainsKey("order_state"))
                    orderRequest.orderState = apiParams["order_state"].ToString();
                if (apiParams.ContainsKey("optional_fields"))
                    orderRequest.optionalFields = apiParams["optional_fields"].ToString();
                if (apiParams.ContainsKey("page"))
                    orderRequest.page = apiParams["page"].ToString();
                if (apiParams.ContainsKey("page_size"))
                    orderRequest.pageSize = apiParams["page_size"].ToString();

                var orderResponse = client.Execute(orderRequest, accessToken, DateTime.Now.ToLocalTime());

                try
                {
                    if (orderResponse.IsError)
                        throw new Exception(orderResponse.ErrMsg);
                    var data = JObject.Parse(orderResponse.Body);
                    var orders = data.GetJsonObject("jingdong_pop_order_search_responce").GetJsonObject("searchorderinfo_result").GetJsonObjectValue("orderInfoList") as JArray;
                    if (orders != null)
                    {
                        var tdeclient = Jd.ACES.TDEClient.GetInstance(url, appKey, appSecret, accessToken);
                        foreach (var item in orders)
                        {
                            JObject order = item as JObject;
                            JObject consigneeInfo = order.GetJsonObject("consigneeInfo");
                            string orderid = order.GetJsonObjectStringValue("orderId");
                            string oaid = consigneeInfo.GetJsonObjectStringValue("oaid");
                            string consignee = oaid;
                            if (string.IsNullOrWhiteSpace(oaid))
                            {
                                string mobile = consigneeInfo.GetJsonObjectStringValue("desen_mobile");
                                string telephone = consigneeInfo.GetJsonObjectStringValue("desen_telephone");
                                string fullname = null;
                                string fullAddress = null;
                                try
                                {
                                    fullname = tdeclient.DecryptString(consigneeInfo.GetJsonObjectStringValue("fullname"));
                                }
                                catch (Exception ex)
                                {
                                    LogHelper.Error(string.Format("{0} decrypt fullname error: {1}", orderid, consigneeInfo.GetJsonObjectStringValue("fullname")), ex);
                                }
                                try
                                {
                                    fullAddress = tdeclient.DecryptString(consigneeInfo.GetJsonObjectStringValue("fullAddress"));
                                }
                                catch (Exception ex)
                                {
                                    LogHelper.Error(string.Format("{0} decrypt fullAddress error: {1}", orderid, consigneeInfo.GetJsonObjectStringValue("fullAddress")), ex);
                                }
                                consignee = fullname + mobile + telephone + fullAddress;
                            }
                            string digest = Utils.MD5(consignee);
                            LogHelper.Info(orderid + ": " + consignee);
                            LogHelper.Info(digest);
                            consigneeInfo["digest"] = digest;
                        }
                    }
                    return data;
                }
                catch (Exception ex)
                {
                    LogHelper.Info("jingdong.pop.order.search error:");
                    LogHelper.Info(orderResponse);
                    throw ex;
                }
            }
            catch (BaseException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                    throw ex;
                throw new Exception(ex.Code);
            }
            catch (Exception ex)
            {
                LogHelper.Info("GetOrderList fail: " + ex.Message);
                throw new Exception("@3001");
            }
        }
    }
}
